import { timeline, logger } from '@/instance'
import {
  Ref,
  ref,
  reactive,
  computed,
  ComputedRef,
  readonly,
  provide,
} from 'vue'
import { getPxPerSec } from '@/console/timeline'

export type TimelineComposition = {
  currentTime: Ref<number>
  updateCurrentTime: (x: number) => void
  duration: Ref<number>
  updateDuration: (x: number) => void
  scale: Ref<number>
  timelinePlayer: typeof timeline
  updateScale: (x: number) => void
  pxPerSec: ComputedRef<number>
}

export function useTimeline(): TimelineComposition {
  logger.log('composables/timeline', 'useTimeline')
  const currentTime = ref(0)
  const updateCurrentTime = (val: number) => {
    timelinePlayer.currentTime = val
    logger.log('composables/timeline', 'updateCurrentTime')
  }

  const duration = ref(24000)
  const updateDuration = (val: number) => (duration.value = val)

  const scale = ref(120)
  const updateScale = (val: number) => (scale.value = val)

  timeline.on('timeupdate', (event) => {
    currentTime.value = event.currentTime
    logger.log('composables/timeline', 'ontimeupdate')
  })


  const timelinePlayer = reactive(timeline) as typeof timeline

  const pxPerSec = computed(() => getPxPerSec(scale.value))

  provide('currentTime', readonly(currentTime))
  provide('updateCurrentTime', updateCurrentTime)

  provide('duration', readonly(duration))
  provide('updateDuration', updateDuration)

  provide('scale', readonly(scale))
  provide('updateScale', updateScale)

  provide('timelinePlayer', timelinePlayer)

  provide('pxPerSec', pxPerSec)

  return {
    currentTime,
    updateCurrentTime,
    duration,
    updateDuration,
    scale,
    updateScale,
    pxPerSec,
    timelinePlayer,
  }
}
